﻿/***
 * This example expects the serial port has a loopback on it.
 *
 * Alternatively, you could use an Arduino:
 *
 * <pre>
 *  void setup() {
 *    Serial.begin(<insert your baudrate here>);
 *  }
 *
 *  void loop() {
 *    if (Serial.available()) {
 *      Serial.write(Serial.read());
 *    }
 *  }
 * </pre>
 */

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <cstdio>
#include <ctime>  
#include <mutex>

// OS Specific sleep
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif

#include "serial/serial.h"
#include "UartWriteFile.h"
#include "MainWidget.h"

using std::string;
using std::exception;
using std::cout;
using std::cerr;
using std::endl;
using std::vector;

void my_sleep(unsigned long milliseconds) {
#ifdef _WIN32
      Sleep(milliseconds); // 100 ms
#else
      usleep(milliseconds*1000); // 100 ms
#endif
}

mutex UARTMutex;

void enumerate_ports()
{
	vector<serial::PortInfo> devices_found = serial::list_ports();

	vector<serial::PortInfo>::iterator iter = devices_found.begin();

	while( iter != devices_found.end() )
	{
		serial::PortInfo device = *iter++;

		printf( "(%s, %s, %s)\n", device.port.c_str(), device.description.c_str(),
     device.hardware_id.c_str() );
	}
}

void print_usage()
{
	cerr << "Usage: test_serial {-e|<serial port address>} ";
    cerr << "<baudrate> [test string]" << endl;
}

void print_time(UartWriteFile FileObj)
{
	SYSTEMTIME	st;
	GetLocalTime(&st);

	char temp_time[64];

	sprintf(temp_time,"[%d/%d/%d %d:%d:%d:%d] ",st.wYear,
		st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);

	cout << temp_time;

	if(FileObj.WriteGetFIleFp() != NULL)
	{
		FileObj.WriteToDataFile(temp_time, strlen(temp_time));
	}
}

void find_port_infor(void)
{
	enumerate_ports();
}

int run(serial::Serial& my_serial, UartWriteFile& SaveFp)
{
	UARTMutex.lock();
	string result = my_serial.read(1);
	UARTMutex.unlock();

	cout << result;
	char ch = *(result.c_str());

	if(SaveFp.WriteGetFIleFp() != NULL)
	{
		SaveFp.WriteToDataFile(&ch, 1);
	}
	if (ch == '\n')
	{
		print_time(SaveFp);
	}

	return 0;
}


int run_send(serial::Serial& my_serial, const uint8_t *data, size_t size)
{
	UARTMutex.lock();
	size_t bytes_wrote = my_serial.write(data, size);
	UARTMutex.unlock();

	return bytes_wrote;
}


#if 0

void serial_example_main()
{
	int ret = 0;

	try {
		ret = run(argc, argv);
		if (ret == -1)
		{
			throw - 1;
		}

	}
	catch (exception &e) {
		cerr << "Unhandled Exception: " << e.what() << endl;
	}
	catch (...)
	{
		cout << "you is dog:" << "catch (...)" << endl;
	}
}
#endif


#if 0
int main(int argc, char **argv)
{
	int ret = 0;

  try {
	  ret = run(argc, argv);
	  if (ret == -1)
	  {
		  throw  -1;
	  }

  } catch (exception &e) {
    cerr << "Unhandled Exception: " << e.what() << endl;
  }
  catch (...)
  {
	  cout << "you is dog:" << "catch (...)" << endl;
  }
  system("pause");
  return 0;
}

#endif
